package com.trailwalker.javafx.core.fragment;

import com.trailwalker.javafx.core.activity.Activity;
import javafx.scene.layout.AnchorPane;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Trailwalker
 * @create 2021-09-05 17:50
 */
public class FragmentManager {

    private AnchorPane mApContainerView;
    private Activity mActivity;
    private final List<FragmentContext> mFragmentList;
    private FragmentManager mFragmentManager;
    private Class mMainFragmentClz;

    public FragmentManager(AnchorPane containerView) {
        mApContainerView = containerView;
        mFragmentList = new ArrayList<>();
        mFragmentManager = this;
    }

    public void setActivity(Activity activity) {
        mActivity = activity;
    }

    public void setMainFragment(Class clz) {
        mMainFragmentClz = clz;
    }

    public Class getMainFragment() {
        return mMainFragmentClz;
    }

    public void startFragment(Class clz) {
        String clzName = clz.getName();
        try {
            Class<?> clzFragment = Class.forName(clzName);
            try {
                Constructor<?> fragmentConstructor = clzFragment.getConstructor();
                try {
                    FragmentContext fragment = (FragmentContext) fragmentConstructor.newInstance();
                    mFragmentList.add(fragment);
                    fragment.setContainerView(mApContainerView);
                    fragment.setFragmentManager(mFragmentManager);
                    fragment.onCreate();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void finish() {
        if (mFragmentList.size() > 1) {
            mFragmentList.remove(mFragmentList.size() - 1);
            FragmentContext fragment = mFragmentList.get(mFragmentList.size() - 1);
            fragment.onRestart();
        }
    }

    public Activity getActivity() {
        return mActivity;
    }

    public boolean onBackPressed() {
        if (mFragmentList.size() > 0) {
            FragmentContext fragment = mFragmentList.get(mFragmentList.size() - 1);
            return fragment.onBackPressed();
        } else {
            return false;
        }
    }

}
